from django.http import JsonResponse
from django.views import View

from users.models import User


class UsernameCountView(View):
    '''用户名重复注册'''

    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取数据失败'})
        if count != 1:
            return JsonResponse({'code': 400,
                                 'errmsg': '用户名已存在'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})


class MobileCountView(View):
    '''手机号重复注册'''

    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取数据失败'})
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})